<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <el-form-item label="标题" prop="title">
                    <el-input
                        v-model="formData.title"
                        placeholder="请输入标题"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                    />
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input
                        v-model="formData.productName"
                        placeholder="请输入商品名称"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                    />
                </el-form-item>
                <el-form-item label="商品简介" prop="productBrief">
                    <el-input
                        v-model="formData.productBrief"
                        placeholder="请输入商品简介"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                    />
                </el-form-item>
                <el-form-item label="商品容量" prop="volume">
                    <el-input v-model="formData.volume" placeholder="请输入商品容量" />
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input v-model="formData.price" placeholder="请输入商品价格" />
                </el-form-item>
                <el-form-item label="是否含税" prop="taxInclusive">
                    <el-input v-model="formData.taxInclusive" placeholder="请输入是否含税" />
                </el-form-item>
                <el-form-item label="主要成分" prop="mainIngredients">
                    <el-input
                        v-model="formData.mainIngredients"
                        placeholder="请输入主要成分"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                    />
                </el-form-item>
                <el-form-item label="商品特点" prop="features">
                    <el-input
                        v-model="formData.features"
                        placeholder="请输入商品特点"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                    />
                </el-form-item>
                <el-form-item label="使用方法" prop="useway">
                    <el-input
                        v-model="formData.useway"
                        placeholder="请输入使用方法"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                    />
                </el-form-item>
                <el-form-item label="宣传图" prop="imageList">
                    <div class="image-upload-container">
                        <div class="flex items-start gap-3">
                            <el-upload
                                :show-file-list="false"
                                :auto-upload="true"
                                :http-request="handleSingleImageUpload"
                                :before-upload="beforeSingleImageUpload"
                                accept="image/*"
                            >
                                <el-button size="small" type="primary" :loading="uploading">
                                    {{ uploading ? '上传中...' : '选择图片' }}
                                </el-button>
                            </el-upload>
                            <div v-if="formData.imageList" class="flex-1">
                                <el-image 
                                    :src="formData.imageList" 
                                    style="width: 100px; height: 100px" 
                                    fit="cover"
                                    :preview-src-list="[formData.imageList]"
                                />
                                <div class="text-xs text-gray-500 mt-1 break-all">{{ formData.imageList }}</div>
                            </div>
                            <el-button 
                                v-if="formData.imageList"
                                type="danger" 
                                size="small" 
                                @click="removeSingleImage"
                            >
                                删除
                            </el-button>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import {  detailsEdit, detailsAdd, detailsDetail } from '@/api/details'
import { uploadImg } from '@/api/uploads'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑商品详情' : '新增商品详情'
})

// 隐藏的id字段
const _id = ref('')

const formData = reactive({
    title: '',
    productName: '',
    productBrief: '',
    volume: '',
    price: '',
    taxInclusive: '',
    mainIngredients: '',
    features: '',
    useway: '',
    imageList: '',
})

const formRules = {
    title: [
        {
            required: true,
            message: '请输入标题',
            trigger: ['blur']
        }
    ],
    productName: [
        {
            required: true,
            message: '请输入商品名称',
            trigger: ['blur']
        }
    ],
    productBrief: [
        {
            required: true,
            message: '请输入商品简介',
            trigger: ['blur']
        }
    ],
    volume: [
        {
            required: true,
            message: '请输入商品容量',
            trigger: ['blur']
        }
    ],
    price: [
        {
            required: true,
            message: '请输入商品价格',
            trigger: ['blur']
        }
    ],
    taxInclusive: [
        {
            required: true,
            message: '请输入是否含税',
            trigger: ['blur']
        }
    ],
    mainIngredients: [
        {
            required: true,
            message: '请输入主要成分',
            trigger: ['blur']
        }
    ],
    features: [
        {
            required: true,
            message: '请输入商品特点',
            trigger: ['blur']
        }
    ],
    useway: [
        {
            required: true,
            message: '请输入使用方法',
            trigger: ['blur']
        }
    ],
    imageList: [
        {
            required: false,
            message: '请上传宣传图',
            trigger: ['blur']
        }
    ],
}

// 图片上传相关方法
const uploading = ref(false)

const beforeSingleImageUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isImage) {
        feedback.msgError('只能上传图片文件!')
        return false
    }
    if (!isLt10M) {
        feedback.msgError('图片大小不能超过 10MB!')
        return false
    }
    return true
}

const handleSingleImageUpload = async (options: any) => {
    uploading.value = true
    try {
        const uploadFormData = new FormData()
        uploadFormData.append('file', options.file)
        
        const response = await uploadImg(uploadFormData)
        if (response && response.url) {
            formData.imageList = response.url
            feedback.msgSuccess('图片上传成功')
        }
    } catch (error) {
        console.error('图片上传失败:', error)
        feedback.msgError('图片上传失败')
    } finally {
        uploading.value = false
    }
}

const removeSingleImage = () => {
    formData.imageList = ''
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }
    // 如果是编辑模式，添加id参数
    if (mode.value == 'edit' && _id.value) {
        data.id = _id.value
    }
    mode.value == 'edit' ? await detailsEdit(data) : await detailsAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    if (type === 'add') {
        // 重置图片
        formData.imageList = ''
    }
    popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
    // 保存id到隐藏变量
    if (data.id) {
        _id.value = data.id
    }
    
    // 处理嵌套的数据结构，常见的后端返回可能有data或result字段
    let actualData = data
    // 如果数据嵌套在data字段中
    if (data.data && typeof data.data === 'object') {
        actualData = data.data
        // 同时检查嵌套数据中的id
        if (actualData.id && !_id.value) {
            _id.value = actualData.id
        }
    }
    // 如果数据嵌套在result字段中
    else if (data.result && typeof data.result === 'object') {
        actualData = data.result
        // 同时检查嵌套数据中的id
        if (actualData.id && !_id.value) {
            _id.value = actualData.id
        }
    }
    
    for (const key in formData) {
        // 先尝试从实际数据中获取
        if (actualData[key] != null && actualData[key] != undefined) {
            //@ts-ignore
            formData[key] = actualData[key]
        }
        // 如果获取不到，再尝试从原始数据中获取
        else if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await detailsDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
